﻿using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Extensions.Caching.Distributed
{
    public static class DistributedCacheExtensions
    {
        public static async Task<T> GetCache<T>(this IDistributedCache cache, string cacheKey) where T : new()
        {
            var onlineUserStr = await cache.GetStringAsync(cacheKey);
            if (!string.IsNullOrEmpty(onlineUserStr))
            {
                return JsonConvert.DeserializeObject<T>(onlineUserStr);
            }
            else
            {
                return Activator.CreateInstance<T>();
            }
        }
        public static async Task SetCache(this IDistributedCache cache, string cacheKey, object value)
        {
            await cache.SetStringAsync(cacheKey,
                    JsonConvert.SerializeObject(value),
                    new DistributedCacheEntryOptions
                    { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12) }
                );
        }
    }
}
